import hashlib
import os
import time
from pprint import pprint

import requests

base_url = 'http://47.108.206.80:18080'


def read_file(file):
    with open(file, 'r', encoding='utf8', errors='ignore') as f:
        return f.read()


def write_file(content, file):
    with open(file, "w", encoding='utf-8') as fw:
        fw.write(content)


def read_or_generate_token():
    token_file = rf'token_file.txt'
    if os.path.isfile(token_file):
        mt = os.path.getmtime(token_file)
        delta_seconds = time.time() - mt
        # print(delta_seconds)
        if delta_seconds < 1 * 3600:
            return read_file(token_file)
        else:
            os.unlink(token_file)
    # token = interactive_generate_token()
    login_url = f"{base_url}/api/user/login"
    response = requests.get(login_url, params={
        "username": "player",
        "password": '02affe1f4b22b8adb3270e1d9c92db96'
    })
    # print(response.url)
    # print(response.text)
    token = response.json()["data"].get("accessToken")
    print(token)
    write_file(token, token_file)
    return token


token = read_or_generate_token()
headers = {
    'access-token': token,
    # "Content-Type": "application/x-www-form-urlencoded"
}
# exit(0)
def query_devices():
    path = '/api/device/query/devices'
    resp = requests.get(f'{base_url}{path}',
                        headers=headers,
                        params={
                            'page': 1,
                            'count': 10,
                            'query': '',
                            'status': True,

                        },
                        timeout=5)
    pprint(resp.json())
    return resp.json()['data']['list']
query_devices()

def query_device_channels(deviceId):
    # ='34020000001320000007'
    path = f'/api/device/query/devices/{deviceId}/channels'
    resp = requests.get(f'{base_url}{path}',
                        headers=headers,
                        params={
                            'page': 1,
                            'count': 10,
                        },
                        timeout=5)
    pprint(resp.json())
    return resp.json()['data']['list']

# query_device_channels('51011500491110000030')
# 25 28

def query_all_channels():
    for device in query_devices():
        device_id = device['deviceId']
        for channel in query_device_channels(device_id):
            yield channel
        # path = f'/api/device/query/devices/{device_id}/channels'
        # resp = requests.get(f'{base_url}{path}',
        #                     headers=headers,
        #                     params={
        #                         'page': 1,
        #                         'count': 10,
        #                     },
        #                     timeout=5)
        # pprint(resp.json())
        # break
def query_all_play_urls():
    for channel in query_all_channels():
        # print(channel)
        device_id= channel['parentId']
        channel_id= channel['deviceId']
        # print(channel)
        url=f'http://47.108.206.80:80/rtp/{device_id}_{channel_id}.live.flv'
        # print(url)
        print(f'"{url}",')
# query_all_play_urls()
def snap_device_channel(deviceId,channelId):
    # deviceId='34020000001320000007'
    # channelId='34020000001310000007'


    # channelId='28'
    #/{deviceId}/{channelId}
    path = f'/api/play/snap'
    resp = requests.get(f'{base_url}{path}',
                        headers=headers,
                        params={
                            'deviceId': deviceId,
                            'channelId': channelId,
                        },
                        timeout=50)
    pprint(resp.json())

def get_device_location(deviceId):
    # deviceId='34020000001320000007'
    # channelId='34020000001310000007'


    # channelId='28'
    #/{deviceId}/{channelId}
    path = f'/api/position/realtime/{deviceId}'
    # path = f'/api/position/latest/{deviceId}'
    resp = requests.get(f'{base_url}{path}',
                        headers=headers,
                        params={
                            'deviceId': deviceId,
                        },
                        timeout=50)
    pprint(resp.json())

# deviceId= '51011500491110000010'
# channelId='34020000001310000012'
# snap_device_channel(deviceId,channelId)
# get_device_location(deviceId)